package cn.fl.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.web.core.framework.constant.SysOrgConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.service.ISysOrgService;
import cn.fl.system.transform.SysOrgVOTransform;
import cn.fl.system.vo.SysOrgVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class SysOrgServiceImpl implements ISysOrgService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(SysOrgServiceImpl.class);

	/**
	 * 组织架构 API 暴露服务
	 */
	@Autowired
	private ISysOrgApiService sysOrgApiService;

	/**
	 * 本地数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;


	@Override
	public SysOrgVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id))return null;
		SysOrgDTO dto = sysOrgApiService.selectSysOrgById(id,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		return SysOrgVOTransform.toVO(dto);
	}

	@Override
	public JSONArray searchList(Long orgPid) throws BaseException {
		if(orgPid==null){
			BaseLogUtils.info(logger, "searchList", "查询组织架构失败,组织架构父ID为空.orgPid:"+orgPid, CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		List<SysOrgDTO> sysOrgDTOPidList = sysOrgApiService.searchSysOrgByOrgPid(orgPid,CurrentThreadContext.getCurrentSysCd());
		List<SysOrgVO> sysOrgVOList = SysOrgVOTransform.toVOList(sysOrgDTOPidList);
		JSONArray sysOrgVoArray = new JSONArray();
		for (SysOrgVO sysOrgVO : sysOrgVOList) {

			JSONObject sysOrgVoObject = new JSONObject();
			Long id = sysOrgVO.getId();
			sysOrgVoObject.put("id", id);//当前节点id
			sysOrgVoObject.put("text", sysOrgVO.getOrgNm());//组织架构全称
			sysOrgVoObject.put("pid", sysOrgVO.getOrgPid());//组织架构pid
			List<SysOrgDTO> sysOrgDTOList = sysOrgApiService.searchSysOrgByOrgPid(id,CurrentThreadContext.getCurrentSysCd());
			if(CollectionUtils.isNotEmpty(sysOrgDTOList)){

				sysOrgVoObject.put("hasChildren",SysOrgConstant.SYS_ORG_ORG_CD_IS_HAV_CHILE_YES );//组织架构是否有子节点
			}else{
				sysOrgVoObject.put("hasChildren",SysOrgConstant.SYS_ORG_ORG_CD_IS_HAV_CHILE_NO );//组织架构是否有子节点
			}
			sysOrgVoArray.add(sysOrgVoObject);
		}

		return sysOrgVoArray;
	}

	@Override
	public Long addSysOrgChild(SysOrgVO entity) throws BaseException {
		if(entity==null){
			BaseLogUtils.info(logger, "addSysOrgChild", "新增子级组织架构失败,组织架构对象为空.DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return sysOrgApiService.addSysOrgChild(SysOrgVOTransform.toDTO(entity));
	}

	@Override
	public List<KeyValueVO> searchSysOrgTypCdList() throws BaseException {
		return this.getKvList(DictionaryConstant.CODE_GRP_SYS_ORG_TYP_CD);
	}

	/*@Override
	public Long add(SysOrgVO entity) throws BaseException{
		if(null == entity)return null;
		return this.sysOrgApiService.add(SysOrgVOTransform.toDTO(entity));
	}*/

	/*@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id))return false;
		return this.sysOrgApiService.removeById(id);
	}*/

	@Override
	public boolean modify(SysOrgVO entity) throws BaseException{
		if(entity==null){
			BaseLogUtils.info(logger, "modify", "修改组织架构信息失败,组织架构对象为空.DATA:"+com.alibaba.fastjson.JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		return this.sysOrgApiService.modifySysOrg(SysOrgVOTransform.toDTO(entity));
	}

	/*@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		return this.sysOrgApiService.searchListPage(page);
	}*/

	/**
	 * 根据字典中代码组值获取组员集合
	 * @param grpCd 代码组值
	 * @return 集合
	 */
	private List<KeyValueVO> getKvList(String grpCd){
		if(StringUtils.isBlank(grpCd)){
			return null;
		}
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if(CollectionUtils.isNotEmpty(sysDictionaryDTOList)){
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.info(logger, "getKvList", "获取字典项组"+grpCd+"失败.grpCd:"+grpCd+".ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "getKvList", "获取字典项组"+grpCd+"失败,系统错误.grpCd:"+grpCd+".ERROR:"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return kvList;
	}

	@Override
	public boolean removeById(Long id) throws BaseException {
		if(id==null){
			BaseLogUtils.info(logger, "removeById", "删除组织架构失败,主键参数为空.ID:"+id, CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		boolean removeResult =false;
		List<SysOrgDTO> sysOrgByOrgPidList = this.sysOrgApiService.searchSysOrgByOrgPid(id,CurrentThreadContext.getCurrentSysCd());
		if(CollectionUtils.isNotEmpty(sysOrgByOrgPidList)){
			for (SysOrgDTO sysOrgDTO : sysOrgByOrgPidList) {
				removeResult = this.sysOrgApiService.removeSysOrgById(sysOrgDTO.getId());
				if(!removeResult){
					removeResult =false;
				}
			}
		}

		removeResult=this.sysOrgApiService.removeSysOrgById(id);
		return  removeResult;
	}

	/**
	 * 递归添加方法
	 */
	private JSONArray setValueToArray(List<SysOrgDTO> list,JSONArray array){

		if(CollectionUtils.isNotEmpty(list)){
			for (SysOrgDTO sysOrgDTO : list) {
				Long id = sysOrgDTO.getId();
				JSONObject jsonObject = new JSONObject ();
				jsonObject.put("id",id );
				jsonObject.put("text",sysOrgDTO.getOrgNm());
				jsonObject.put("pid", sysOrgDTO.getOrgPid());//组织架构pid
				List<SysOrgDTO> childrenList = this.sysOrgApiService.searchSysOrgByOrgPid(id,CurrentThreadContext.getCurrentSysCd());
				if(CollectionUtils.isNotEmpty(childrenList)){
					JSONArray jsonArray2 = setValueToArray(childrenList, new JSONArray());
					jsonObject.put("children",jsonArray2);
				}
				array.add(jsonObject);

			}
		}
		return array;
	}

	@Override
	public JSONArray searchOrgTreeByOrgNm(String orgNm, String sysCd) throws BaseException{
		List<SysOrgDTO> orgList = this.sysOrgApiService.searchOrgTreeByOrgNm(orgNm, sysCd);
		JSONArray jsonArray = new JSONArray ();
		if(CollectionUtils.isEmpty(orgList)){
			return jsonArray;
		}
		for (SysOrgDTO sysOrgDTO : orgList) {
			JSONObject obj = new JSONObject();
			obj.put("ischecked", false);
			obj.put("id", sysOrgDTO.getId());
			obj.put("text", sysOrgDTO.getOrgNm());
			obj.put("pid", sysOrgDTO.getOrgPid());
			obj.put("orgCd", sysOrgDTO.getOrgCd());
			obj.put("orgDispNm", sysOrgDTO.getOrgDispNm());
			jsonArray.add(obj);
		}
		JSONArray treeList = this.treeList(jsonArray,SysOrgConstant.SYS_ORG_CD_PID_INIT);
		return treeList;
	}

	@Override
	public JSONArray searchOrgTreeByOrgCon(String orgNm,String orgTypCd, String sysCd) throws BaseException{
		List<SysOrgDTO> orgList = this.sysOrgApiService.searchOrgTreeByOrgCon(orgNm,orgTypCd, sysCd);
		JSONArray jsonArray = new JSONArray ();
		if(CollectionUtils.isEmpty(orgList)){
			return jsonArray;
		}
		for (SysOrgDTO sysOrgDTO : orgList) {
			JSONObject obj = new JSONObject();
			obj.put("ischecked", false);
			obj.put("id", sysOrgDTO.getId());
			obj.put("text", sysOrgDTO.getOrgNm());
			obj.put("pid", sysOrgDTO.getOrgPid());
			obj.put("orgCd", sysOrgDTO.getOrgCd());
			obj.put("orgDispNm", sysOrgDTO.getOrgDispNm());
			jsonArray.add(obj);
		}
		JSONArray treeList = this.treeList(jsonArray,SysOrgConstant.SYS_ORG_CD_PID_INIT);
		return treeList;
	}

	@Override
	public JSONArray searchOrgTreeByOrg(String orgCd,String orgTypCd, String sysCd) throws BaseException{
		List<SysOrgDTO> orgList = this.sysOrgApiService.searchOrgTreeByOrg(orgCd,orgTypCd, sysCd);
		JSONArray jsonArray = new JSONArray ();
		if(CollectionUtils.isEmpty(orgList)){
			return jsonArray;
		}
		for (SysOrgDTO sysOrgDTO : orgList) {
			JSONObject obj = new JSONObject();
			obj.put("ischecked", false);
			obj.put("id", sysOrgDTO.getId());
			obj.put("orgTypeCd", sysOrgDTO.getOrgTypCd());
			obj.put("text", sysOrgDTO.getOrgNm());
			obj.put("pid", sysOrgDTO.getOrgPid());
			obj.put("orgCd", sysOrgDTO.getOrgCd());
			obj.put("orgDispNm", sysOrgDTO.getOrgDispNm());
			jsonArray.add(obj);
		}
		JSONArray treeList = this.treeList(jsonArray,SysOrgConstant.SYS_ORG_CD_PID_INIT);
		return treeList;
	}


	/**
	 * 递归添加整个集合数据
	 *
	 * @param treeList
	 * @param parentId
	 * @return
	 */
	private JSONArray treeList(List treeList, Long parentId) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "treeList", "获取机构树开始");

		List list = this.treeList1(treeList, parentId.toString());
		JSONArray rtnArray = JSONArray.fromObject(list);
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "treeList", "获取机构树.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());

		return rtnArray;
	}

	/**
	 * 递归添加整个集合数据
	 *
	 * @param treeList
	 * @param parentId
	 * @return
	 */
	private List treeList1(List<Map<String, Object>> treeList, String parentId) {
		List childMenu = new ArrayList();
		for (Map object : treeList) {
			String oid = object.get("id").toString();
			String pid = object.get("pid").toString();
			if (parentId.equals(pid)) {
				List c_node = treeList1(treeList, oid);
				object.put("children", c_node);
				childMenu.add(object);
			}
		}
		return childMenu;
	}

	@Override
	public JSONArray searchOrgTreeByCurrentUser(String currentBuOrgCd, String currentSysCd) throws BaseException {
		JSONArray jsonArray = new JSONArray ();
		SysOrgDTO sysOrgDto  = null;
		if(StringUtils.isNotBlank(currentBuOrgCd)){
			List<SysOrgDTO> orgList  = null;
			sysOrgDto = 	this.sysOrgApiService.selectSysOrgByOrgCd(currentBuOrgCd,currentSysCd);
			List<Long> orgId = new ArrayList<Long>();
			orgId.add(sysOrgDto.getId());
			if(null!=sysOrgDto){
				orgList = this.sysOrgApiService.searchRecuOrgWithchildBy(orgId, currentSysCd);
			}
			if(CollectionUtils.isEmpty(orgList)){
				return jsonArray;
			}
			for (SysOrgDTO sysOrgDTO : orgList) {
				JSONObject obj = new JSONObject();
				obj.put("ischecked", false);
				obj.put("id", sysOrgDTO.getId());
				obj.put("text", sysOrgDTO.getOrgNm());
				obj.put("pid", sysOrgDTO.getOrgPid());
				obj.put("orgCd", sysOrgDTO.getOrgCd());
				obj.put("orgDispNm", sysOrgDTO.getOrgDispNm());
				jsonArray.add(obj);
			}
		}
		JSONArray treeList = this.treeList(jsonArray,sysOrgDto.getOrgPid());
		return treeList;
	}

	@Override
	public List<SysOrgVO> searchListByOrgTypCd(String orgTypCd, String sysCd) throws BaseException {
		List<SysOrgDTO> sysOrgDTOList = sysOrgApiService.searchListByOrgTypCd(orgTypCd, sysCd);
		if(sysOrgDTOList != null && sysOrgDTOList.size() >0){
			return SysOrgVOTransform.toVOList(sysOrgDTOList);
		}else{
			return null ;
		}
	}

	@Override
	public List<SysOrgVO> searchListByOrgTypCd(String sysCd) throws BaseException {
		List<SysOrgDTO> sysOrgDTOList = sysOrgApiService.searchListByOrgTypCd(sysCd);
		if(sysOrgDTOList != null && sysOrgDTOList.size() >0){
			return SysOrgVOTransform.toVOList(sysOrgDTOList);
		}else{
			return null ;
		}
	}

	@Override
	public SysOrgVO selectSysOrgByOrgCd(String nodeOrgCd, String flServiceSysCd) {
		if (StringUtils.isEmpty(nodeOrgCd)){
			return null;
		}
		SysOrgDTO dto = this.sysOrgApiService.selectSysOrgByOrgCd(nodeOrgCd,flServiceSysCd);
		SysOrgVO vo = SysOrgVOTransform.toVO(dto);
		return vo;
	}

	@Override
	public List<KeyValueVO> searchBusinessOrgList() throws BaseException {
		List<SysOrgDTO> list = this.sysOrgApiService.searchListByOrgTypCd(CurrentThreadContext.getFlServiceSysCd());
		List<KeyValueVO> kvList = new ArrayList<KeyValueVO>();
		if (CollectionUtils.isEmpty(list)) {
			return kvList;
		}
		for (SysOrgDTO sysOrgDTO : list) {
			KeyValueVO kv = new KeyValueVO();
			kv.setKey(sysOrgDTO.getOrgCd());
			kv.setValue(sysOrgDTO.getOrgNm());
			kvList.add(kv);
		}
		return kvList;
	}


	@Override
	public Map<String,String> searchBusinessOrgMap() throws BaseException {
		List<SysOrgDTO> list = this.sysOrgApiService.searchListByOrgTypCd(CurrentThreadContext.getFlServiceSysCd());
		Map<String,String> orgMap=new HashMap<>();
		for (SysOrgDTO sysOrgDTO : list) {
			orgMap.put(sysOrgDTO.getOrgCd(),sysOrgDTO.getOrgNm());
		}
		return orgMap;
	}
}
